package com.zdb.java.misc;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class GetUsafeInstance {

    private static Unsafe unsafe = null;

    public static Unsafe getInstance() {
        if(unsafe == null) {
            Unsafe unsafe = null;
            try {
                Field f = Unsafe.class.getDeclaredField("theUnsafe");
                f.setAccessible(true);
                // 这里本来就是静态变量，所以不需要加同步锁，最多就是多反射调用一次
                unsafe = (Unsafe) f.get(null);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
            return unsafe;
        } else {
            return unsafe;
        }
    }
}
